/*
 * @Author: 梁辉
 * @Date: 2021-06-15 10:19:03
 * @LastEditors: 梁辉
 * @LastEditTime: 2021-06-16 11:22:50
 * @Description: 
 */
"use strict";
var FUNC_ERROR_TEXT = 'Expected a function';

/**
 * @description: 函数节流
 * @param {Function} func 函数
 * @param {Number} wait 延迟执行毫秒数
 * @param {Boolean} type true 表示时间戳版，false 表示定时器版
 * @return {Function}
 */
function throttle(func, wait, type) {
    if (typeof func != 'function') {
        throw new TypeError(FUNC_ERROR_TEXT)
    }
    
    let previous, timeout
    if (type) {
        previous = 0
    } else {
        timeout
    }

    return function () {
        let context = this
        let args = arguments
        if (type) {
            let now = Date.now()
            if (now - previous > wait) {
                typeof func === 'function' && func.apply(context, args)
                previous = now
            }
        } else {
            if (!timeout) {
                timeout = setTimeout(() => {
                    timeout = null
                    typeof func === 'function' && func.apply(context, args)
                }, wait)
            }
        }
    }
}
